package com.runa.monitor.platinterface.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ctg.ag.sdk.biz.AepDeviceCommandClient;
import com.ctg.ag.sdk.biz.aep_device_command.CreateCommandRequest;
import com.ctg.ag.sdk.biz.aep_device_command.CreateCommandResponse;
import com.runa.monitor.comm.pojo.NBOrder;
import com.runa.monitor.platinterface.extend.nb.config.LKBMqttNbIotConfig;
import com.runa.monitor.platinterface.extend.nb.config.MqttNbIotConfig;
import com.runa.monitor.platinterface.extend.nb.config.NewMqttNbIotConfig;
import com.runa.monitor.platinterface.extend.nb.vo.*;
import com.runa.monitor.platinterface.extend.nb.vo.lkb.DataReportDTO;
import com.runa.persistence.DateUtil;
import com.runa.persistence.StringUtil;
import com.runa.persistence.service.CommNbCmdService;
import com.runa.persistence.util.LogUtil;
import com.runa.protocol.util.UtilTime;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 2025/4/10 10:49
 * zhangYB
 */
@Slf4j
@Service
public class NbSendService {


    @Resource
    private MqttNbIotConfig mqttNbIotConfig;
    @Resource
    private NewMqttNbIotConfig newMqttNbIotConfig;
    @Resource
    private LKBMqttNbIotConfig lkbMqttNbIotConfig;
    @Resource
    private CommNbCmdService commNbCmdService;



    public void validateWakeupCycle(String id, NBOrder nbOrder, String wakeupCycle) {
        try {
            if (null != nbOrder.getWakeupCycle() && nbOrder.getWakeupCycle().equals(wakeupCycle)) {
                nbOrder.setWakeupCycle(null);
                commNbCmdService.clearWakeupCycle(id);
            }
        } catch (Exception e) {
            log.error("validateWakeupCycle: {} {} {} ", id, wakeupCycle, JSON.toJSONString(nbOrder));
        }
    }

    public void validateWakeupCycle(String id, NBOrder nbOrder, NewReportDataBaseVo reportBaseDTO) {
        try {
            if (null != nbOrder) {
                NewMqttRuiPanelVo mqttPanelVo = reportBaseDTO.getPayload();
                String wakeupCycle = String.valueOf(mqttPanelVo.getUp_data_interval());
                validateWakeupCycle(id, nbOrder, wakeupCycle);
            }
        } catch (Exception e) {
            log.error("validateWakeupCycle: {} {} {} ", id, JSON.toJSONString(nbOrder), JSON.toJSONString(reportBaseDTO));
        }
    }

    public void validateWakeupCycle(String id, NBOrder nbOrder, boolean heatingPeriod, String uitv1, String uitv2) {
        try {
            if (null != nbOrder && null != nbOrder.getWakeupCycle()) {
                if (heatingPeriod) {
                    validateWakeupCycle(id, nbOrder, uitv1);
                } else {
                    validateWakeupCycle(id, nbOrder, uitv2);
                }
            }
        } catch (Exception e) {
            log.error("validateWakeupCycle: {} {} {} {} {} ", id, heatingPeriod, uitv1, uitv2, JSON.toJSONString(nbOrder));
        }
    }

    /**
     * 小瑞面板
     * @param id
     * @param reportBaseDTO
     */
    public void sendDxCmdOfXiaoRui(String id, NewReportDataBaseVo reportBaseDTO) {
        try {
            NBOrder nbOrder = commNbCmdService.getNBOrder(id);
            if (null == nbOrder) {
                return;
            }
            validateWakeupCycle(id, nbOrder, reportBaseDTO);
            sendDownCommand(reportBaseDTO.getDeviceId(), reportBaseDTO.getProductId(), newMqttNbIotConfig.getAppKey()
                    , newMqttNbIotConfig.getAppSecret(), newMqttNbIotConfig.getRuiPanelMasterKey(), getDxCmdOfXiaoRui(reportBaseDTO, nbOrder));
        } catch (Exception e) {
            log.error("sendDxCmdOfXiaoRui: {} {} {}", id, JSON.toJSONString(reportBaseDTO), e);
        }
    }

    /**
     * RU面板
     * @param id
     * @param baseVo
     * @param hot
     * @param uitv1
     * @param uitv2
     */
    public void sendCmdReal(String id, ReportDataBaseVo baseVo, String hot, String uitv1, String uitv2) {
        try {
            boolean heatingPeriod = DateUtil.heatingPeriod(hot);
            NBOrder nbOrder = commNbCmdService.getNBOrder(id);
            if (null == nbOrder) {
                return;
            }
            validateWakeupCycle(id, nbOrder, heatingPeriod, uitv1, uitv2);
            sendCmdReal(baseVo.getDeviceId(), baseVo.getProductId(), mqttNbIotConfig.getAppKey()
                    , mqttNbIotConfig.getAppSecret(), mqttNbIotConfig.getRuPanelMasterKey()
                    , getDxCmdOfRU(nbOrder, heatingPeriod), mqttNbIotConfig.getHost());
        } catch (Exception e) {
            log.error("sendCmdReal: {} {} {} {} {} {}", id, hot, uitv1, uitv2, JSON.toJSONString(baseVo), e);
        }
    }

    /**
     * 浪卡博面板
     * 未找到上报唤醒周期，暂时不做唤醒周期判断
     * @param id
     * @param baseVo
     */
    public void sendCmdToLkbTemperature(String id, DataReportDTO baseVo) {
        try {
            NBOrder nbOrder = commNbCmdService.getNBOrder(id);
            sendCmdReal(baseVo.getDeviceId(), baseVo.getProductId(), lkbMqttNbIotConfig.getAppKey()
                    , lkbMqttNbIotConfig.getAppSecret(), lkbMqttNbIotConfig.getPanelMasterKey()
                    , getDxCmdOfLangKaBoPanel(nbOrder));
        } catch (Exception e) {
            log.error("sendCmdToLkbTemperature: {} {}", id, JSON.toJSONString(baseVo));
        }
    }

    /**
     * 瑞纳普通面板
     * @param id
     * @param baseVo
     * @param period
     */
    public void sendCmdToRunaTemperature(String id, ReportDataBaseVo baseVo, String period) {
        try {
            NBOrder nbOrder = commNbCmdService.getNBOrder(id);
            if (null != nbOrder) {
                validateWakeupCycle(id, nbOrder, period);
                sendCmdReal(baseVo.getDeviceId(), baseVo.getProductId(), mqttNbIotConfig.getAppKey()
                        , mqttNbIotConfig.getAppSecret(), mqttNbIotConfig.getPanelMasterKey()
                        , getDxCmd(nbOrder));
            }
        } catch (Exception e) {
            log.error("sendCmdToRunaTemperature: {} {} {}", id, period, JSON.toJSONString(baseVo));
        }

    }


    /**
     * 温压
     * @param id
     * @param baseVo
     * @param serialNo
     * @param stateCode
     * @param uitv
     */
    public void sendCmdToTemperaturePressure(String id, ReportDataBaseVo baseVo, String serialNo, String stateCode, String uitv) {
        try {
            NBOrder nbOrder = commNbCmdService.getNBOrder(id);
            if (null == nbOrder) {
                return;
            }
            validateWakeupCycle(id, nbOrder, uitv);
            sendCmdReal(baseVo.getDeviceId(), baseVo.getProductId(), mqttNbIotConfig.getAppKey()
                    , mqttNbIotConfig.getAppSecret(), mqttNbIotConfig.getTemperaturePressureMasterKey()
                    , getDxCmdOfTemperaturePressure(nbOrder, serialNo, stateCode));
        } catch (Exception e) {
            log.error("sendCmdToTemperaturePressure: {} {} {} {} {}", id, serialNo, stateCode, uitv, JSON.toJSONString(baseVo));
        }


    }

    /**
     * 瑞纳温压
     * 未找到上报唤醒周期，暂时不做唤醒周期判断
     * @param id
     * @param baseVo
     * @param serialNo
     * @param stateCode
     */
    public void sendCmdToRunaTemperaturePressure(String id, ReportDataBaseVo baseVo, String serialNo, String stateCode) {
        try {
            NBOrder nbOrder = commNbCmdService.getNBOrder(id);
            sendCmdReal(baseVo.getDeviceId(), baseVo.getProductId(), mqttNbIotConfig.getAppKey()
                    , mqttNbIotConfig.getAppSecret(), mqttNbIotConfig.getTemperaturePressureMasterKey()
                    , getDxCmdOfTemperaturePressure(nbOrder, serialNo, stateCode));
        } catch (Exception e) {
            log.error("sendCmdToRunaTemperaturePressure: {} {} {} {}", id, serialNo, stateCode, JSON.toJSONString(baseVo));
        }

    }

    /**
     * 阀
     * @param id
     * @param baseVo
     * @param uitv1
     */
    public void sendCmdToValve(String id, ReportDataBaseVo baseVo, String uitv1) {
        try {
            NBOrder nbOrder = commNbCmdService.getNBOrder(id);
            if (null == nbOrder) {
                return;
            }
            validateWakeupCycle(id, nbOrder, uitv1);
            sendCmdReal(baseVo.getDeviceId(), baseVo.getProductId(), mqttNbIotConfig.getAppKey(baseVo.getProductId())
                    , mqttNbIotConfig.getAppSecret(baseVo.getProductId()), mqttNbIotConfig.getBuildValveMasterKey(baseVo.getProductId())
                    , getDxCmdOfBuildValve(nbOrder));
        } catch (Exception e) {
            log.error("sendCmdToValve: {} {} {}", id, uitv1, JSON.toJSONString(baseVo));
        }


    }

    /**
     * 表
     * @param id
     * @param baseVo
     * @param sample
     */
    public void sendCmdToMeter(String id, ReportDataBaseVo baseVo, String sample) {
        try {
            NBOrder nbOrder = commNbCmdService.getNBOrder(id);
            if (null == nbOrder) {
                return;
            }
            validateWakeupCycle(id, nbOrder, sample);
            sendCmdReal(baseVo.getDeviceId(), baseVo.getProductId(), mqttNbIotConfig.getAppKey()
                    , mqttNbIotConfig.getAppSecret(), mqttNbIotConfig.getBuildMeterMasterKey(baseVo.getProductId())
                    , getDxCmdOfBuildMeter(nbOrder));
        } catch (Exception e) {
            log.error("sendCmdToMeter: {} {} {}", id, sample, JSON.toJSONString(baseVo));
        }

    }

    /**
     * 楼阀变温压
     * @param id
     * @param baseVo
     */
    public void sendCmdToBuildValveTe(String id, ReportDataBaseVo baseVo, String citv1) {
        try {
            NBOrder nbOrder = commNbCmdService.getNBOrder(id);
            if (null == nbOrder) {
                return;
            }
            validateWakeupCycle(id, nbOrder, citv1);
            sendCmdReal(baseVo.getDeviceId(), baseVo.getProductId(), mqttNbIotConfig.getAppKey()
                    , mqttNbIotConfig.getAppSecret(), mqttNbIotConfig.getBuildValveTtemperaturePressureMasterKey()
                    , getDxCmdOfBuildValve(nbOrder));
        } catch (Exception e) {
            log.error("sendCmdToBuildValveTe: {} {} {}", id, citv1, JSON.toJSONString(baseVo));
        }


    }

    public void sendRtcCmd(String deviceId, String productId, String APP_KEY, String APP_SECRET, String MASTER_KEY, String host) {
        log.info("{} {} 下发校时", deviceId, productId);
        sendCmdReal(deviceId, productId, APP_KEY, APP_SECRET, MASTER_KEY, getRtcCmd(), host);
    }

    public void sendRtcCmd(String deviceId, String productId, String APP_KEY, String APP_SECRET, String MASTER_KEY) {
        log.info("{} {} 下发校时", deviceId, productId);
        sendCmdReal(deviceId, productId, APP_KEY, APP_SECRET, MASTER_KEY, getRtcCmd());
    }

    private String getRtcCmd() {
        return "rtc:" + UtilTime.getCurrentTime("yyyyMMddHHmmss");
    }

    private String getDxCmdOfBuildMeter(NBOrder nbOrder) {
        List<SendCmdParamVo> sendCmdParamVoList = getDxCmdOfMode(nbOrder);
        if (nbOrder != null && nbOrder.getWakeupCycle() != null) {
            sendCmdParamVoList.add(new SendCmdParamVo("sample:", nbOrder.getWakeupCycle()));
            sendCmdParamVoList.add(new SendCmdParamVo("report:", nbOrder.getWakeupCycle()));
        }
        sendCmdParamVoList.add(new SendCmdParamVo("rtc:", UtilTime.getCurrentTime("yyyyMMddHHmmss")));
        if (CollectionUtils.isEmpty(sendCmdParamVoList)) {
            return "";
        }
        String sendContent = null;
        sendContent = finalGen(sendCmdParamVoList, sendContent);
        return sendContent;
    }

    private String getDxCmdOfTemperaturePressure(NBOrder nbOrder, String serialNo, String stateCode) {
        List<SendCmdParamVo> sendCmdParamVoList = getDxCmdOfMode(nbOrder);
        sendCmdParamVoList.add(new SendCmdParamVo("rtc:", UtilTime.getCurrentTime("yyyyMMddHHmmss")));
        if (nbOrder != null && nbOrder.getWakeupCycle() != null) {
            sendCmdParamVoList.add(new SendCmdParamVo("citv:", nbOrder.getWakeupCycle() + "_" + nbOrder.getWakeupCycle()));//采样周期  数据1：供暖季  数据2：非供暖季 单位minutes
            sendCmdParamVoList.add(new SendCmdParamVo("uitv:", nbOrder.getWakeupCycle() + "_" + nbOrder.getWakeupCycle()));//冻结周期  数据1：供暖季  数据2：非供暖季 单位minutes
            sendCmdParamVoList.add(new SendCmdParamVo("sitv:", nbOrder.getWakeupCycle() + "_" + nbOrder.getWakeupCycle()));//上报周期  数据1：供暖季  数据2：非供暖季 单位minutes
        }
        if (nbOrder != null && nbOrder.getCompensation() != null)
            sendCmdParamVoList.add(new SendCmdParamVo("Tc:", Double.valueOf(nbOrder.getCompensation()) * 10 + "_0"));//采样周期  数据1：供暖季  数据2：非供暖季 单位minutes
        if (stateCode.equals("80007800") && serialNo.startsWith("24")) {
            //1、更新设备模式
            sendCmdParamVoList.add(new SendCmdParamVo("sta:", "80007800"));
        }
        if (CollectionUtils.isEmpty(sendCmdParamVoList)) {
            return "";
        }
        String sendContent = null;
        sendContent = finalGen(sendCmdParamVoList, sendContent);
        return sendContent;
    }

    private String getDxCmdOfBuildValve(NBOrder nbOrder) {
        List<SendCmdParamVo> sendCmdParamVoList = getDxCmdOfMode(nbOrder);
        sendCmdParamVoList.add(new SendCmdParamVo("rtc:", UtilTime.getCurrentTime("yyyyMMddHHmmss")));
        if (nbOrder != null && nbOrder.getWakeupCycle() != null) {
            sendCmdParamVoList.add(new SendCmdParamVo("citv1:", nbOrder.getWakeupCycle()));
            sendCmdParamVoList.add(new SendCmdParamVo("uitv1:", nbOrder.getWakeupCycle()));
            sendCmdParamVoList.add(new SendCmdParamVo("citv2:", nbOrder.getWakeupCycle()));
            sendCmdParamVoList.add(new SendCmdParamVo("uitv2:", nbOrder.getWakeupCycle()));
        }
        if (nbOrder != null && nbOrder.getOpen() != null)
            sendCmdParamVoList.add(new SendCmdParamVo("set:", new BigDecimal(nbOrder.getOpen()).setScale(1, RoundingMode.HALF_UP).toString()));
        if (nbOrder != null && nbOrder.getCmdType() != null)
            if (nbOrder.getCmdType().equals("1")) {
                sendCmdParamVoList.add(new SendCmdParamVo("par:", "0008"));
            } else if (nbOrder.getCmdType().equals("2")) {
                sendCmdParamVoList.add(new SendCmdParamVo(" kdcal:", "1"));
            }
//            sendCmdParamVoList.add(new SendCmdParamVo("set:", new BigDecimal(commNbcmd.getOpen()).setScale(1, RoundingMode.HALF_UP).toString()));
        if (CollectionUtils.isEmpty(sendCmdParamVoList)) {
            return "";
        }
        String sendContent = null;
        sendContent = finalGen(sendCmdParamVoList, sendContent);
        return sendContent;
    }


    private String getDxCmdOfLangKaBoPanel(NBOrder nbOrder) {
        List<SendCmdParamVo> sendCmdParamVoList = new ArrayList<>();
        //较时
        sendCmdParamVoList.add(new SendCmdParamVo("rtc:", UtilTime.getCurrentTime("yyyyMMddHHmmss")));
        if (nbOrder != null && nbOrder.getCompensation() != null)
            sendRoomPanlCompen(sendCmdParamVoList, nbOrder.getCompensation());
        if (CollectionUtils.isEmpty(sendCmdParamVoList)) {
            return "";
        }
        String sendContent = getSendCmdByParamList(sendCmdParamVoList);
        return sendContent;
    }


    /**
     * 获取下发指令内容
     *
     * @param sendCmdParamVoList 下发指令参数
     * @return 下发指令内容
     */
    public static String getSendCmdByParamList(List<SendCmdParamVo> sendCmdParamVoList) {
        String sendContent = null;
        if (!CollectionUtils.isEmpty(sendCmdParamVoList)) {
            for (SendCmdParamVo sendCmdParamVo : sendCmdParamVoList) {
                if (StringUtils.isBlank(sendContent)) {
                    sendContent = sendCmdParamVo.getParamKey() + sendCmdParamVo.getParamValue();
                } else {
                    sendContent = sendContent + "," + sendCmdParamVo.getParamKey() + sendCmdParamVo.getParamValue();
                }
            }
        }
        return sendContent;
    }

    private String getDxCmd(NBOrder nbOrder) {
        List<SendCmdParamVo> sendCmdParamVoList = getDxCmdOfMode(nbOrder);
        addCheckTimeCmd(sendCmdParamVoList);
        if (nbOrder != null && nbOrder.getWakeupCycle() != null)
            addWakeUpCycleCmd(sendCmdParamVoList, nbOrder.getWakeupCycle());
        if (nbOrder != null && nbOrder.getCompensation() != null)
            sendRoomPanlCompen(sendCmdParamVoList, nbOrder.getCompensation());
        if (CollectionUtils.isEmpty(sendCmdParamVoList)) {
            return "";
        }
        String sendContent = null;
        sendContent = finalGen(sendCmdParamVoList, sendContent);
        return sendContent;
    }

    private String getDxCmdOfRU(NBOrder nbOrder, boolean heatingPeriod) {
        List<SendCmdParamVo> sendCmdParamVoList = getDxCmdOfMode(nbOrder);
        sendCmdParamVoList.add(new SendCmdParamVo("rtc:", UtilTime.getCurrentTime("yyyyMMddHHmmss")));
        if (nbOrder != null && nbOrder.getWakeupCycle() != null) {
            if (heatingPeriod) {
                sendCmdParamVoList.add(new SendCmdParamVo("uitv1:", nbOrder.getWakeupCycle()));
                sendCmdParamVoList.add(new SendCmdParamVo("sitv1:", nbOrder.getWakeupCycle()));
            } else {
                sendCmdParamVoList.add(new SendCmdParamVo("uitv2:", nbOrder.getWakeupCycle()));
                sendCmdParamVoList.add(new SendCmdParamVo("sitv2:", nbOrder.getWakeupCycle()));
            }
        }
        if (nbOrder != null && nbOrder.getCompensation() != null)
            sendCmdParamVoList.add(new SendCmdParamVo("Tc:", nbOrder.getCompensation()));
        if (CollectionUtils.isEmpty(sendCmdParamVoList)) {
            return "";
        }
        String sendContent = null;
        sendContent = finalGen(sendCmdParamVoList, sendContent);
        log.debug("nbOrder: {} sendContent: {}", JSON.toJSONString(nbOrder), sendContent);
        return sendContent;
    }

    private String finalGen(List<SendCmdParamVo> sendCmdParamVoList, String sendContent) {
        if (!CollectionUtils.isEmpty(sendCmdParamVoList)) {
            for (SendCmdParamVo sendCmdParamVo : sendCmdParamVoList) {
                if (StringUtils.isBlank(sendContent)) {
                    sendContent = sendCmdParamVo.getParamKey() + sendCmdParamVo.getParamValue();
                } else {
                    sendContent = sendContent + "," + sendCmdParamVo.getParamKey() + sendCmdParamVo.getParamValue();
                }
            }
        }
        return sendContent;
    }


    private List<SendCmdParamVo> getDxCmdOfMode(NBOrder nbOrder) {
        List<SendCmdParamVo> sendCmdParamVoList =  new ArrayList<>();
        if (null != nbOrder) {
            String mode = nbOrder.getMode();
            if (null != mode) {
                sendCmdParamVoList.add(new SendCmdParamVo("mode:", mode));
            }
        }
        return sendCmdParamVoList;
    }

    /**
     * 真正的发送
     */
    private void sendCmdReal(String deviceId, String productId, String APP_KEY, String APP_SECRET, String MASTER_KEY, String cmd, String host) {
        log.debug("deviceId:{} productId:{} APP_KEY:{} APP_SECRET:{} MASTER_KEY:{} host:{} 下发指令 {}", deviceId, productId, APP_KEY, APP_SECRET, MASTER_KEY, host, cmd);
        if (StringUtil.isNotBlank(host)) {
            AepDeviceCommandClient client = AepDeviceCommandClient.newClient().host(host)
                    .appKey(APP_KEY).appSecret(APP_SECRET)
                    .build();
            sendCmdReal(client, deviceId, productId, MASTER_KEY, cmd);
        } else {
            sendCmdReal(deviceId, productId, APP_KEY, APP_SECRET, MASTER_KEY, cmd);
        }
    }

    private void sendCmdReal(String deviceId, String productId, String APP_KEY, String APP_SECRET, String MASTER_KEY, String cmd) {
        AepDeviceCommandClient client = AepDeviceCommandClient.newClient()
                .appKey(APP_KEY).appSecret(APP_SECRET)
                .build();
        sendCmdReal(client, deviceId, productId, MASTER_KEY, cmd);
    }

    private void sendCmdReal(AepDeviceCommandClient client, String deviceId, String productId, String MASTER_KEY, String cmd) {
        SendCmdDetailVo sendCmdDetailVo = new SendCmdDetailVo();
        //代表字符串
        sendCmdDetailVo.setDataType(1);
        sendCmdDetailVo.setPayload(cmd);
        CreateCommandRequest request = new CreateCommandRequest();
        request.setParamMasterKey(MASTER_KEY);
        SendCmdBaseVo sendBaseVo = new SendCmdBaseVo();
        sendBaseVo.setDeviceId(deviceId);
        //operator: 操作者，必填
        sendBaseVo.setOperator("RUNA_COMM_NODE");
        sendBaseVo.setProductId(productId);
        //设备指令缓存时长，选填。单位：秒，取值范围：0-864000。 不携带则默认值：7200。如不需缓存请填0
        sendBaseVo.setTtl(7200);
        sendBaseVo.setContent(sendCmdDetailVo);
        String body = JSONObject.toJSONString(sendBaseVo);
        log.info("masterKey:{} productId:{} deviceId:{} 电信平台下发请求:{}", MASTER_KEY, productId, deviceId, body);
        request.setBody(body.getBytes());
        CreateCommandResponse commandResponse = null;
        try {
            LogUtil.getLogAndInfo("nbCmd", "CMD", "MASTER_KEY {} 下发指令 {} ", MASTER_KEY, body);
            commandResponse = client.CreateCommand(request);
        } catch (Exception e) {
            log.error("", e);
        }
        String responseMsg = new String(commandResponse.getBody(), StandardCharsets.UTF_8);
        LogUtil.getLogAndInfo("nbCmd", "CMD", "productId {} deviceId {} 结果: {}", productId, deviceId, responseMsg);
        log.info("masterKey:{} productId:{} deviceId:{} 电信平台返回结果:{}", MASTER_KEY, productId, deviceId, responseMsg);
        client.shutdown();
    }


    public String sendDownCommand(String deviceId, String productId, String APP_KEY, String APP_SECRET, String MASTER_KEY, String cmd) {
        NewSendCmdDetailVo sendCmdDetailVo = new NewSendCmdDetailVo();
        //代表字符串
        sendCmdDetailVo.setServiceIdentifier("humiture_setup");
        sendCmdDetailVo.setParams(cmd);
        String responseMsg = null;
        try {
            AepDeviceCommandClient client = AepDeviceCommandClient.newClient()
                    .appKey(APP_KEY).appSecret(APP_SECRET)
                    .build();
            CreateCommandRequest request = new CreateCommandRequest();
            request.setParamMasterKey(MASTER_KEY);
            NewSendCmdBaseVo sendBaseVo = new NewSendCmdBaseVo();
            sendBaseVo.setDeviceId(deviceId);
            //operator: 操作者，必填
            sendBaseVo.setOperator("RUNA_SMART_EQUIPMENT");
            sendBaseVo.setProductId(productId);
            //设备指令缓存时长，选填。单位：秒，取值范围：0-864000。 不携带则默认值：7200。如不需缓存请填0
            sendBaseVo.setTtl(7200);
            sendBaseVo.setContent(sendCmdDetailVo);
            String body = JSONObject.toJSONString(sendBaseVo);
//            log.info(sendCmdConfigVo.getTipMessage() + "---下发指令内容为：" + body);
            request.setBody(body.getBytes());
            CreateCommandResponse commandResponse = client.CreateCommand(request);
            responseMsg = new String(commandResponse.getBody(), StandardCharsets.UTF_8);
            log.info("电信平台---下发命令返回的结果：{}", responseMsg);
            client.shutdown();
        } catch (Exception ex) {
            ex.printStackTrace();
            log.info(deviceId + "---下发命令失败：" + ex.getMessage());
        }
        return responseMsg;
    }


    private String getDxCmdOfXiaoRui(NewReportDataBaseVo reportBaseDTO, NBOrder nbOrder) {
        net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
        addCheckTimeCmd(reportBaseDTO.getPayload().getSoft_version(), jsonObject);
        jsonObject.put("up_data_interval", reportBaseDTO.getPayload().getUp_data_interval().toString());
        jsonObject.put("save_data_interval", reportBaseDTO.getPayload().getSave_data_interval().toString());
        if (nbOrder != null && nbOrder.getWakeupCycle() != null) {
            addWakeUpCycleCmd(jsonObject, nbOrder.getWakeupCycle());
        }
        jsonObject.put("temp_offset", "0");
        if (nbOrder != null && nbOrder.getCompensation() != null) {
            addCompensationCommand(nbOrder.getCompensation(), jsonObject);
        }
        jsonObject.put("humidity_offset", reportBaseDTO.getPayload().getHumidity_offset().toString());
        jsonObject.put("lessee_code", reportBaseDTO.getPayload().getLessee_code().toString());
        return jsonObject.toString();
    }

    /**
     * 下发唤醒周期
     */
    public static void addWakeUpCycleCmd(net.sf.json.JSONObject jsonObject, String wakeUpCycle) {
//            if (null != wakeUpCycle && checkCanSendWakeUpCycle(wakeUpCycleAddTime)) {
        if (null != wakeUpCycle) {
            jsonObject.put("up_data_interval", wakeUpCycle);
            jsonObject.put("save_data_interval", wakeUpCycle);
        }
    }

    /**
     * 下发唤醒周期-下发命令 对于透传设备，无法到达指令已完成状态，指令的最终状态即为指令已送达
     */
    public static void addWakeUpCycleCmd(List<SendCmdParamVo> sendCmdParamVoList, String wakeUpCycle) {
        sendCmdParamVoList.add(new SendCmdParamVo("period:", wakeUpCycle));
    }

    private static void addCompensationCommand(String compensation, net.sf.json.JSONObject jsonObject) {
        //值1代表0.1  小瑞面板乘10 只取整数部分
        BigDecimal c = new BigDecimal(compensation).multiply(new BigDecimal(10));
        //只取整数部分
        jsonObject.put("temp_offset", c.intValue());
    }

    /**
     * 设备校时时间
     */
    public static void addCheckTimeCmd(String soft_version, net.sf.json.JSONObject jsonObject) {
        long now = System.currentTimeMillis();
        if ("V1.0.0".equals(soft_version)) {
            now = (now / 1000) + (24 * 60 * 60);
        } else {
            now = now / 1000;
        }
        jsonObject.put("updatetime", now + "");
    }


    /**
     * 设备校时时间-校时，大于1分钟校时
     */
    public static void addCheckTimeCmd(List<SendCmdParamVo> sendCmdParamVoList) {
        //较时
        sendCmdParamVoList.add(new SendCmdParamVo("rtc:", UtilTime.getCurrentTime("yyyyMMddHHmmss")));
    }

    private void sendRoomPanlCompen(List<SendCmdParamVo> sendCmdParamVoList, String compensation) {
        sendCmdParamVoList.add(new SendCmdParamVo("Tc:", compensation));
    }
}
